const event = (G as any).misc.AppEvent;
import { PanLogic } from '../PanLogic'

export class DistributeMap extends event {
    private options: any;
    private map: any;
    private layerConfig: any;
    // private restWMSService: any;
    private restHttp: any;
    private sickLayer: any;
    private populationLayer: any;
    private sickLayerListener: any;
    private sickLayerIsShow: boolean;
    private populationLayerIsShow: boolean;
    private panLogic: any;
    private lastDistrictCode: any;

    constructor(options: any) {
        super();
        this.options = options;
        this.map = options.map;
        this.layerConfig = this.options.mapConfig.distributeLayers;
        this.sickLayerIsShow = false;
        this.populationLayerIsShow = false;
        this.sickLayerListener = this.commonSickLayerListener.bind(this);
        this.map.on("click", this.sickLayerListener);
        this.panLogic = new PanLogic(this.options);
    }

    public addSickMap(districtCode: string) {
        if (this.lastDistrictCode === districtCode) {
            return;
        }
        this.lastDistrictCode = districtCode;
        this.panLogic.fit(districtCode);
        const type = this.panLogic.getDistrictLevel(districtCode);
        if (type < 3) {
            this.removeSickMap();
        }
        let disCodeSufix;
        switch (type) {
            case 0:
                this.sickLayer = this.addWmsLayer(this.layerConfig.provinceSick);
                this.sickLayer.config = this.layerConfig.provinceSick;
                break;
            case 1:
                disCodeSufix = districtCode.slice(0, 2);
                this.layerConfig.citySick.cqlFilter = encodeURIComponent("code like " + "'" + disCodeSufix + "%" + "'");
                this.sickLayer = this.addWmsLayer(this.layerConfig.citySick);
                this.sickLayer.config = this.layerConfig.citySick;
                break;
            case 2:
                // 直辖市做特殊处理
                if (/(11|12|31|50)[0]{4}/.test(districtCode)) {
                    disCodeSufix = districtCode.slice(0, 2) + '01';
                } else {
                    disCodeSufix = districtCode.slice(0, 4);
                }

                this.layerConfig.countySick.cqlFilter =
                    encodeURIComponent("code like " + "'" + disCodeSufix + "%" + "'");
                this.sickLayer = this.addWmsLayer(this.layerConfig.countySick);
                this.sickLayer.config = this.layerConfig.countySick;
                break;
            default:
                break;
        }
    }

    public removeSickMap() {
        const layerNames = [this.layerConfig.provinceSick.name, this.layerConfig.citySick.name,
        this.layerConfig.countySick.name];
        layerNames.forEach((name) => {
            this.removeWmsLayer(name);
        })
    }

    public addPopulationMap() {
        if (!this.populationLayer) {
            this.populationLayer = this.addWmsLayer(this.layerConfig.cityPopulation);
        }

    }


    public removePopulationMap() {
        const layerName = this.layerConfig.cityPopulation.name;
        this.removeWmsLayer(layerName);
        this.populationLayer = null;
    }

    public showSickMap() {
        if (this.sickLayer) {
            this.sickLayer.setVisible(true);
            this.sickLayerIsShow = true;
        }
    }

    public hideSickMap() {
        if (this.sickLayer) {
            this.sickLayer.setVisible(false);
            this.sickLayerIsShow = false;
        }
    }

    public showPopulationMap() {
        if (this.populationLayer) {
            this.populationLayer.setVisible(true);
            this.populationLayerIsShow = true;
        }
    }

    public hidePopulationMap() {
        if (this.populationLayer) {
            this.populationLayer.setVisible(false);
            this.populationLayerIsShow = false;
        }
    }

    // 卸载地图事件,图层
    public destroy() {
        this.removePopulationMap();
        this.removeSickMap();
        this.map.un("click", this.sickLayerListener);
    }


    private commonSickLayerListener(button: number, shift: boolean, screenX: number,
                                    screenY: number, mapX: number, mapY: number, handle: boolean) {
        if (!this.sickLayer) {
            return;
        }
        const options = {
            url: this.sickLayer.config.url,
            projection: this.sickLayer.config.projection,
            name: this.sickLayer.config.layers,
            style: this.sickLayer.config.style,
            filter: this.sickLayer.config.cqlFilter || '1=1',
            screenX,
            screenY
        }

        this.getFeatureInfo.call(this, options);
    }

    private addWmsLayer(options: any): any {
        const layer = new g2.carto.TileLayer(options);
        // 添加前先移除旧图层
        // this.removeWmsLayer(layer.name);
        this.map.addLayer(layer);
        this.initWMSService();
        return layer;
    }

    private removeWmsLayer(layerName: string) {
        const map = this.options.map;
        const layer = map.findLayer(layerName);
        if (!!layer) {
            map.removeLayer(layer);
        }
    }

    private initWMSService() {
        /*        this.restWMSService = new g2.ews.RestWMSService({
                    url: this.options.url
                });*/
        this.restHttp = new g2.core.RestHttp({});
    }


    private getFeatureInfo(options: any) {
        let getFeatureInfoUrl = options.url;
        getFeatureInfoUrl += "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image%2Fpng&INFO_FORMAT=text%2Fhtml&FEATURE_COUNT=50";
        const SRS = options.projection;
        const QUERY_LAYERS = options.name;
        const STYLES = options.style;
        const envelope = this.options.map.getExtent(); // 获取当前地图的范围
        const viewSize = this.options.map.getViewSize(); //
        const WIDTH = viewSize[0];// 以像素为单位的地图图像宽度
        const HEIGHT = viewSize[1]; //
        const X = Math.floor(options.screenX);
        const Y = Math.floor(options.screenY);
        const BBOX = this.covertGeometry(envelope);
        const FILTER = options.filter;

        // http://106.37.227.19:38200/geoserver/jyxxxzqh/wms?
        // SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image%2Fpng
        // &QUERY_LAYERS=jyxxxzqh%3Agis_regionalism_province_utf82
        // &LAYERS=jyxxxzqh%3Agis_regionalism_province_utf82&INFO_FORMAT=text%2Fhtml&FEATURE_COUNT=50&X=50&Y=50&
        // SRS=EPSG%3A4326&STYLES=&WIDTH=101&HEIGHT=101
        // &BBOX=109.36230629682541%2C25.514648035168655%2C118.23925942182541%2C34.391601160168655

        getFeatureInfoUrl += "&SRS=" + SRS + "&QUERY_LAYERS=" + QUERY_LAYERS + "&LAYERS=" + QUERY_LAYERS + "&X=" + X + "&Y=" + Y + "&WIDTH=" + WIDTH + "&HEIGHT=" + HEIGHT + "&BBOX=" + BBOX + "&CQL_FILTER=" + FILTER;
        const promise = this.restHttp.get(getFeatureInfoUrl);
        promise.then((result: any) => {
            const districtCode = this.parseResult.call(self, result);
            if (districtCode) {
                this.fire('districtchange', { districtCode })
            }
            // self.addSickMap(districtCode);
            // self.sickLayerIsShow ? self.showSickMap() : self.hideSickMap();
        })

        /*const districtCode = "42000"; // 模拟数据
        this.addSickMap(districtCode);*/
    }

    // 解析要素查询结果
    private parseResult(result: any): any {
        if (!!result) {
            const el = document.createElement('html');
            el.innerHTML = result;
            const table = el.getElementsByTagName("table")[0];
            if (!!table) {
                const headers = table.rows[0].children;
                let index = 0;
                for (let i = 0, len = headers.length; i < len; i++) {
                    const content = headers[i].innerHTML;
                    if (content === "code") {
                        index = i;
                    }
                }
                return table.rows[1].children[index].innerHTML; //

            }
        }
    }


    private covertGeometry(extent: any) {
        if (!!extent) {
            return extent.minx + ',' + extent.miny + ',' + extent.maxx + ',' + extent.maxy;
        }
    }
}
